package isjinhao.jlox.grammar.expression.visitor;

import isjinhao.jlox.grammar.expression.represention.*;

/**
 * @Author ISJINHAO
 * @Date 2021/2/20 21:49
 */
public class RPNExpressionVisitor implements ExpressionVisitor<String> {

    public String print(Expression expression) {
        return expression.accept(this);
    }

    @Override
    public String visitArithmeticExpr(Arithmetic expr) {
        return parenthesize(expr.getOperator().getLexeme(), expr.getLeft(), expr.getRight());
    }

    @Override
    public String visitGroupingExpr(Grouping expr) {
        // 直接忽略 Group 这种类型，执行其内部的表达式
        return expr.getExpression().accept(this);
    }

    @Override
    public String visitLiteralExpr(Literal expr) {
        if (expr.getValue() == null) {
            return "nil";
        }
        return expr.getValue().toString();
    }

    @Override
    public String visitUnaryExpr(Unary expr) {
        return parenthesize(expr.getOperator().getLexeme(), expr.getRight());
    }

    /**
     * 后序遍历
     * @param name
     * @param expressions
     * @return
     */
    private String parenthesize(String name, Expression... expressions) {
        StringBuilder builder = new StringBuilder();

        for (Expression expression : expressions) {
            builder.append(expression.accept(this));
            builder.append(" ");
        }
        builder.append(name);

        return builder.toString();
    }

}
